package sim;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Stack;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import prepro.SerializeStopWordObject;
import prepro.SerializeTermsToInt;
import tWeight.TfIdf;
import matrics.SparseVector;
import myLucene.GetTime;
import myLucene.Props;

public class StartSimDist {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		long start = System.currentTimeMillis();
		String targetPath = "/local/joofeit/backIdioms_6/Dist";
								
		File targetFile = new File(targetPath);
		Directory iDirectory = FSDirectory.open(new File(Props.readIndexPath));
		IndexSearcher searcher = new IndexSearcher(iDirectory, true);
		IndexReader iReader = searcher.getIndexReader();
		Stack<Integer> stops = SerializeStopWordObject.deserializeStops();

		String[] intToTerms = SerializeTermsToInt.deserializeArray();
		if (targetFile.isDirectory()) {
			File[] targetFiles = targetFile.listFiles();
			Collections.sort(Arrays.asList(targetFiles));

			for (File target : targetFiles) {
				long startFile = System.currentTimeMillis();
				String curTerm = target.getName()
						.substring(0, (target.getName().length()- 13));
				System.out.println("++++++++++++++++++++++++++++++++++++++++++"
						+ curTerm + " " + target.getAbsolutePath());
			
				LinkedList<Integer>[] targetArray = ReadObject.readLinkedListArray(target.getCanonicalPath());
				HashMap<Integer, Double> results = Sim.startSimDist(target,targetArray,stops, intToTerms);
				System.out
						.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Time needed... "
								+ GetTime.getDuration(startFile, System
										.currentTimeMillis()) + " " + curTerm);
				resultsToFile(results, curTerm, intToTerms);
			}
		}
		System.out.println("StartSim: Time needed... "
				+ GetTime.getDuration(start, System.currentTimeMillis()));
	}

	public static void resultsToFile(HashMap<Integer, Double> results,
			String curTerm, String[] intToTerms) throws IOException {
		BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
				"/local/joofeit/results_Dist_" + Props.windowSize + "/results_Dist"
						+ Props.windowSize + "_" +Props.smoothingDistWeight+"_" +curTerm)));
		for (int i : results.keySet()) {
			bw.write(results.get(i) + " " + intToTerms[i] + " " + i + " "
					+ curTerm + "\n");
		}
		bw.flush();
		bw.close();
	}

}